package grabana

import (
	
	
	
	
	
)

// ErrAPIKeyNotFound is returned when the given API key can not be found.
var ErrAPIKeyNotFound = errors.New("API key not found")

// APIKeyRole represents a role given to an API key.
type APIKeyRole uint8

const (
	AdminRole APIKeyRole = iota
	EditorRole
	ViewerRole
)

func ( APIKeyRole) () ([]byte, error) {
	var  string
	switch  {
	case ViewerRole:
		 = "Viewer"
	case EditorRole:
		 = "Editor"
	case AdminRole:
		 = "Admin"
	default:
		 = "None"
	}

	return json.Marshal()
}

// CreateAPIKeyRequest represents a request made to the API key creation endpoint.
type CreateAPIKeyRequest struct {
	Name          string     `json:"name"`
	Role          APIKeyRole `json:"role"`
	SecondsToLive int        `json:"secondsToLive"`
}

// APIKey represents an API key.
type APIKey struct {
	ID   uint   `json:"id"`
	Name string `json:"name"`
}

// CreateAPIKey creates a new API key.
func ( *Client) ( context.Context,  CreateAPIKeyRequest) (string, error) {
	,  := json.Marshal()
	if  != nil {
		return "", 
	}

	,  := .sendJSON(, http.MethodPost, "/api/auth/keys", )
	if  != nil {
		return "", 
	}

	defer func() { _ = .Body.Close() }()

	if .StatusCode != http.StatusOK {
		return "", .httpError()
	}

	var  struct {
		 string `json:"key"`
	}
	if  := decodeJSON(.Body, &);  != nil {
		return "", 
	}

	return ., nil
}

// DeleteAPIKeyByName deletes an API key given its name.
func ( *Client) ( context.Context,  string) error {
	,  := .APIKeys()
	if  != nil {
		return 
	}

	,  := []
	if ! {
		return ErrAPIKeyNotFound
	}

	,  := .delete(, fmt.Sprintf("/api/auth/keys/%d", .ID))
	if  != nil {
		return 
	}

	defer func() { _ = .Body.Close() }()

	if .StatusCode == http.StatusNotFound {
		return ErrAPIKeyNotFound
	}
	if .StatusCode != http.StatusOK {
		return .httpError()
	}

	return nil
}

// APIKeys lists active API keys.
func ( *Client) ( context.Context) (map[string]APIKey, error) {
	,  := .get(, "/api/auth/keys")
	if  != nil {
		return nil, 
	}

	defer func() { _ = .Body.Close() }()

	if .StatusCode != http.StatusOK {
		return nil, .httpError()
	}

	var  []APIKey
	if  := decodeJSON(.Body, &);  != nil {
		return nil, 
	}

	 := make(map[string]APIKey, len())
	for ,  := range  {
		[.Name] = 
	}

	return , nil
}